import { login } from '@/api/user'
import { Message } from 'element-ui'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

const state = {
  token: getToken() || ''
}

const mutations = {
  logout(state) {
    state.userItem = {}
    state.token = ''
    removeToken()
    router.push('/login')
  },
  getToken(state, newToken) {
    // 存到VUEX
    state.token = newToken
    // 存到Cookie
    setToken(newToken)
  }
}

const actions = {
  async login(context, payloap) {
    const res = await login(payloap)
    const token = res.data.token.token
    context.commit('getToken', token)
    // console.log(res)
    if (res.msg === 'ok') {
      Message.success('登录成功')
      router.push('/')
    }
  },
  outlogo(context) {
    context.commit('logout')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

